import { useActionState } from "react";
function App() {
  //  使用useActionState处理表单状态和提交
  //  state 表单状态对象
  //  formAction 表单提交处理函数
  //  pending 表单是否正在提交
  const [state, formAction, pending] = useActionState(
    //异步处理表单提交的函数 formAction
    async (currentState, formData) => {
      const name = formData.get("name");
      const email = formData.get("email");
      const password = formData.get("password");
      // 校验
      if (!password || password.length < 6) {
        // return 是给 state 赋值
        return {
          error: { message: "密码长度不能小于6位!" },
          data: currentState.data,
        };
      }
      // 发起请求
      await new Promise((resolve) => setTimeout(resolve, 2000));
      // return 是给 state 赋值
      return {
        error: null,
        data: {
          message: "注册成功",
          name,
          email,
        },
      };
    },

    // 下方对象，是一个初始的状态 state
    {
      data: {},
      error: null,
    }
  );
  return (
    <div>
      <form action={formAction}>
        <div>
          <label>姓名:</label>
          <input
            type="text"
            id="name"
            name="name"
            required
            disabled={pending}
          />
        </div>
        <div>
          <label>邮箱:</label>
          <input
            type="text"
            id="email"
            name="email"
            required
            disabled={pending}
          />
        </div>
        <div>
          <label>密码:</label>
          <input
            type="password"
            id="password"
            name="password"
            required
            disabled={pending}
          />
        </div>
        <button type="submit" disabled={pending}>
          {pending ? "提交中..." : "提交"}
        </button>
      </form>
      {state.error && <div style={{ color: "red" }}>{state.error.message}</div>}
      {state.data && <div style={{ color: "green" }}>{state.data.message}</div>}
    </div>
  );
}
export default App;
/**
 * 表单提交
 * 以前本来就有两种思路
 * 1.非受控组件  ref
 * 2.使用受控组件 state
 */
